package com.dyz.leetcode;

public class ReverseList206 {
    //使用迭代的方法
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){return head;}
        ListNode pre =null;
        ListNode cur = head;
        while (cur!=null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public ListNode reverseList1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList1(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode Listnode = new ListNode(0);    //创建首节点，节点的val是0.
        ListNode nextNode;                     //声明一个变量用来在移动过程中指向当前节点
        nextNode=Listnode;                      //指向首节点

        //创建链表
        for(int i=1;i<6;i++){
            ListNode node = new ListNode(i);  //生成新的节点
            nextNode.next=node;               //把新节点连起来
            nextNode=nextNode.next;           //当前节点往后移动
        }       //当for循环完成之后 nextNode指向最后一个节点，

        nextNode=Listnode;                     //重新赋值让它指向首节点
        new ReverseList206().reverseList1(nextNode);

    }
}
